<template>
  <div class="register-container">
    <van-form @submit="handleSubmit">
      <h2>注册</h2>
      <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请输入用户名' }]"
        class="custom-field"
      />
      <van-field
        v-model="realName"
        name="真实姓名"
        label="真实姓名"
        placeholder="真实姓名"
        :rules="[{ required: true, message: '请输入真实姓名' }]"
        class="custom-field"
      />
      <van-field
        v-model="phone"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' },
        ]"
        class="custom-field"
      />
      <van-field
        v-model="email"
        name="邮箱"
        label="邮箱"
        placeholder="邮箱"
        :rules="[
          { required: true, message: '请输入邮箱' },
          {
            pattern: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,
            message: '请输入正确的邮箱格式',
          },
        ]"
        class="custom-field"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请输入密码' },
          { min: 6, message: '密码长度至少为6位' },
        ]"
        class="custom-field"
      />
      <van-uploader v-model="avatar" name="头像" :after-read="afterRead" />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >注册</van-button
        >
      </div>
      <div style="text-align: center; margin-top: 8px">
        <router-link to="/login">已有账号？去登录</router-link>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { Toast } from "vant";
import { useUserStore } from "@/store/userStore"; // 假设你有一个用户存储
import { userRegisterService } from "@/api/user"; // 假设你有一个注册服务

const router = useRouter();
const userStore = useUserStore();

const username = ref("");
const realName = ref("");
const phone = ref("");
const email = ref("");
const password = ref("");
const avatar = ref([]);
const loading = ref(false);

const handleSubmit = async () => {
  try {
    if (!(await validateForm())) return;

    loading.value = true;
    const registerResult = await performRegister();
    handleRegisterResponse(registerResult);
  } catch (error) {
    handleError(error);
  } finally {
    loading.value = false;
  }
};

const validateForm = async () => {
  try {
    return await form.value.validate();
  } catch {
    Toast.fail("表单验证失败");
    return false;
  }
};

const performRegister = async () => {
  return await userRegisterService({
    username: username.value,
    realName: realName.value,
    phoneNumber: phone.value,
    email: email.value,
    password: password.value,
    avatarUrl: avatar.value,
  });
};

const handleRegisterResponse = (result) => {
  if (result.code === 1) {
    Toast.success(result.message || "注册成功");
    userStore.setUser(result.data);
    router.push("/login");
  } else {
    Toast.fail(result.message || "注册失败");
  }
};

const handleError = (error) => {
  console.error(
    "Error during registration:",
    error.response?.data || error.message
  );
  Toast.fail("服务错误");
};

const afterRead = (file) => {
  // 这里可以处理上传后的文件
  console.log(file);
};
</script>

<style scoped>
.register-container {
  background-color: #f0f9eb;
  padding: 20px;
  border-radius: 8px;
  max-width: 400px;
  margin: auto;
  margin-top: 50px;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  color: #07c160;
  text-align: center;
  margin-bottom: 20px;
}

/* 美化输入框 */
.custom-field {
  width: 100%;
  border: 2px solid #ced4da;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 16px;
  background-color: #fff;
  transition: border-color 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
}

.custom-field:focus-within {
  border-color: #07c160;
  box-shadow: 0 0 0 0.2rem rgba(7, 193, 96, 0.25);
}

.custom-field .van-field__label {
  color: #495057;
  font-weight: 500;
}

.custom-field .van-field__control::placeholder {
  color: #adb5bd;
  font-size: 0.9rem;
}

/* 美化按钮 */
.van-button {
  width: 100%;
  background-color: #07c160;
  border: none;
  transition: background-color 0.3s ease-in-out;
}

.van-button:hover {
  background-color: #059d58;
}

/* 登录链接 */
a {
  color: #07c160;
  text-decoration: none;
  transition: color 0.3s ease-in-out;
}

a:hover {
  color: #059d58;
}

/* 上传区域 */
.van-uploader {
  width: 100%;
  margin-bottom: 16px;
}

.van-uploader__upload {
  width: 100%;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 2px dashed #ced4da;
  border-radius: 8px;
  transition: border-color 0.3s ease-in-out;
}

.van-uploader__upload:hover {
  border-color: #07c160;
}

.van-uploader__upload-icon {
  font-size: 24px;
  color: #ced4da;
}

.van-uploader__upload-text {
  color: #ced4da;
  margin-top: 8px;
}
</style>